package com.taotao.job.rpc.core.utils;

import com.google.common.base.Preconditions;
import com.taotao.job.rpc.core.invoker.RpcInvokerException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author fanbeibei
 * @date 2020/11/1 20:03
 */
public class ReflectUtil {
    private ReflectUtil() {
    }

    /**
     * obj 是否是iface的实现类的对象
     *
     * @param obj
     * @param ifaceClass
     * @return
     */
    public static boolean isImplementsFor(Object obj, Class<?> ifaceClass) {
        Preconditions.checkArgument(null != obj);
        Preconditions.checkArgument(null != ifaceClass);
        if (!ifaceClass.isInterface()) {
            throw new IllegalArgumentException("ifaceClass is not  interface");
        }

        Class<?>[] implIfaceClasses = obj.getClass().getInterfaces();
        if (CollectionUtils.isEmpty(implIfaceClasses)) {
            return false;
        }

        return Arrays.asList(implIfaceClasses).contains(ifaceClass);
    }


    public static Method getMethod(Class<?> srcClass, String methodName, Class<?>[] argTypes) throws RpcInvokerException {

        Preconditions.checkArgument(null != srcClass);
        Preconditions.checkArgument(StringUtils.isNotBlank(methodName));

        try {
            return srcClass.getMethod(methodName, argTypes);
        } catch (NoSuchMethodException e) {
            throw new RpcInvokerException(e.getMessage());
        }
    }


    public static Object invokeIface(Object ifaceImpl, Method method, Object... args) throws RpcInvokerException {
        Preconditions.checkArgument(null != ifaceImpl);
        Preconditions.checkArgument(null != method);

        try {
            return method.invoke(ifaceImpl, args);
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new RpcInvokerException(e.getMessage());
        }
    }
}
